<?php
if ( !defined('IN_SCRIPT') ) { header("Location: index.php"); exit; }
if(LOGGED_IN) { header("Location: $current_location/$index_script"); exit;}

$page_title = $lang['forgot_title']; 
$smarty->assign('content', 'forgot_pass');
  
if ($REQUEST_METHOD == 'POST') {
    if($mode == 'send_link') {
        $email = (field_validator($lang['email'], $email, "email", 5, 100) ? $email : '');
        $row = check_user($email);
        if(($email != '') && $row) {
            $hash = md5(time().mt_rand().$email);
            db_query("UPDATE `users` SET `hash_forgot_pass` = '$hash' where `email`='$email'");
            // DONE: проверить отправку на почту
            $chpass_lnk = "$current_location/$index_script?$place_name=forgot&h=$hash"; 
            fn_mail($email, $lang['change_psw_subject'], sprintf($lang['change_psw_body'], $row['first_name'], $chpass_lnk, $chpass_lnk));
            $lang['send_new_pass_msg'] = sprintf($lang['send_new_pass_msg'], $email);
            $smarty->assign('email', $email); 
            $smarty->assign('content', 'pass_sent');
        } else {
            if(!$messages) add_message($lang['wrong_email']);
            $smarty->assign('have_errors', true);
        }
    } elseif ($mode == 'set_new_pass')
        if(field_validator($lang['password'], $_POST["password"], "string", 3, 20) && 
           field_validator($lang['email'], $email, "email", 5, 100) &&
           db_query("UPDATE `users` SET `pass`='".md5($_POST["password"])."', `hash_forgot_pass`='' WHERE `email`='$email' AND `hash_forgot_pass`='$hh'")) {
            
            $result = db_query("SELECT * FROM `users` WHERE `email`='$email'");
            $row=mysql_fetch_array($result);
            cleanMemberSession($row);
            header("Location: $current_location/$index_script");
            exit;
        } else {
            header("Location: $current_location/$index_script?$place_name=forgot&h=$hh&e=".rand()); 
            exit;
        }
    
} 

if(get_param('h') != '' && field_validator('hash', get_param('h'), 'alphanumeric', 5, 64))
{
    $result = db_query("SELECT * FROM `users` WHERE `hash_forgot_pass` = '".get_param('h')."'");
    if(mysql_num_rows($result)==1) {
        $row=mysql_fetch_array($result);
        
        if (get_param('e') != '') {
            add_message($lang['reenter_pass']);
            $smarty->assign('have_errors', true); 
        }
        $smarty->assign('first_name', $row['first_name']); 
        $smarty->assign('email', $row['email']); 
        $smarty->assign('hash_forgot_pass', $row['hash_forgot_pass']);
        $smarty->assign('content', 'new_pass');
    }
}
?>
